package team.knowers.qzhserver.course.datum.file.service.Impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.knowers.qzhserver.course.datum.file.entity.dao.FileDO;
import team.knowers.qzhserver.course.datum.file.entity.dto.FileUploadDTO;
import team.knowers.qzhserver.course.datum.file.mapper.FileMapper;
import team.knowers.qzhserver.course.datum.file.service.FileCacheService;
import team.knowers.qzhserver.course.datum.file.service.FileService;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author zcb
 * @date 2024/3/9 21:30
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    FileMapper fileMapper;
    @Override
    public FileDO uploadFile(FileUploadDTO fileUploadDTO) {
        FileDO fileDO = FileDO.builder()
                .courseDatumId(fileUploadDTO.getCdid())
                .name(fileUploadDTO.getName())
                .userId(fileUploadDTO.getUid())
                .gmtCreate(new Date())
                .url(fileUploadDTO.getUrl()).build();
        fileMapper.insert(fileDO);
        return fileDO;
    }

    @Override
    public Boolean deleteFile(String id) {
        FileDO fileDO = getFileById(id);
        if(fileDO==null)
            return false;
        getCacheService().delFile(id);
        getCacheService().delDatumFileSet(fileDO.getCourseDatumId(),fileDO.getId());
        return fileMapper.deleteById(fileDO)==1;
    }

    @Override
    public FileDO getFileById(String id) {
        //先从缓存中查找
        FileDO fileDO = getCacheService().getFile(id);
        if(fileDO==null){
            //缓存中查找不到时从数据库中查找
            fileDO=fileMapper.selectById(id);
            if(fileDO==null){
                //依然查找不到时查找失败
                return null;
            }
        }
        //更新缓存并返回对象
        getCacheService().setFile(fileDO);
        getCacheService().setDatumFileSet(fileDO.getCourseDatumId(),id);
        return fileDO;
    }

    @Override
    public FileCacheService getCacheService() {
        return SpringUtil.getBean(FileCacheService.class);
    }

    @Override
    public Set<String> getDatumFileSet(String cdid) {
        //先从缓存中获取
        Set<String> output = getCacheService().getDatumFileSet(cdid);
        if(output.isEmpty()){
            //从缓存中获取不到时，从数据库中获取
            List<FileDO> fileDOS = fileMapper.selectList(new QueryWrapper<FileDO>().eq("course_datum_id",cdid));
            for(FileDO fileDO:fileDOS){
                output.add(fileDO.getId());
            }
        }
        return output;
    }

}
